package com.lmu.travel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lmu.travel.entity.Order;
import com.lmu.travel.entity.Result;
import com.lmu.travel.entity.Route;
import com.lmu.travel.service.OrderService;
import com.lmu.travel.service.RouteService;
import com.lmu.travel.service.WXPayService;
import com.lmu.travel.util.PayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author liuxuhuang
 * @className: OrderController
 * @description: 订单接口
 * @email liuxuhuang3970@qq.com
 * @date 2021/6/29 20:57
 * @version：1.0
 */
@Api(tags = "订单接口")
@RestController
@RequestMapping("order")
public class OrderController {
    @Resource
    private WXPayService wxPayService;
    @Resource
    private RouteService routeService;
    @Resource
    private OrderService orderService;

    @GetMapping(value = "findOrderOne/{rid}")
    @ApiImplicitParam(name = "rid", value = "订单id", required = true, dataType = "Integer")
    public Result<Order> findOrderOne(@PathVariable("rid") Integer rid) {
        if (rid <= 0) {
            rid = 1;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("rid", rid);
        Route route = routeService.getOne(queryWrapper);
        return new Result<Order>(200, true, route, "查询订单成功");
    }

    @PostMapping(value = "addOrder")
    @ApiOperation("添加订单")
    public Result<Order> addOrder(Order order) throws Exception {
        String out_trade_no = PayUtil.getId("01");
        String payment = order.getPayment() + "";
        String money = PayUtil.getMoney(payment);
        Map<String, String> aNative = null;
        aNative = wxPayService.createNative(out_trade_no, money, order.getGoods());
        if (!("SUCCESS".equals(aNative.get("return_code")) && "SUCCESS".equals(aNative.get("result_code")))) {
            return new Result<Order>(201, false, null, "订单创建失败");
        }
        order.setOrderid(out_trade_no);
        orderService.save(order);
        aNative.put("orderId", out_trade_no);
        aNative.put("total_fee", money);
        return new Result<Order>(200, true, aNative, "创建成功");
    }

    @ApiOperation("查询订单状态")
    @PostMapping(value = "findPayStatus")
    @ApiImplicitParam(name = "orderid", value = "订单id", dataType = "String", required = true)
    public Result<Order> findPayStatus(@PathVariable("orderid") String orderid) {
        Map<String, String> map = wxPayService.queryNative(orderid);
        if (map == null) {
            return new Result<Order>(201, false, "-1", "支付错误");
        }
        if (map.get("trade_status").equals("SUCCESS") && map.get("return_code").equals("SUCCESS") && map.get("result_code").equals("SUCCESS")) {
            orderService.updateStatusSuccess(orderid);
            return new Result<Order>(200, true, null, "支付成功");
        }
        Order order = orderService.findByOrderId(orderid);
        long createTime = order.getCreatetime().getTime();
        long currentTime = System.currentTimeMillis();
        if ((currentTime - createTime) > 1000 * 5 * 60) {
            return close(orderid);
        }
        return new Result<Order>(201, false, "0", "未支付");
    }

    @RequestMapping(value = "/close", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("关闭订单支付")
    private Result close(String orderId) {
        Map closeMap = wxPayService.closeNative(orderId);
        if (closeMap == null || closeMap.get("return_code").equals("FAIL")) {
            return new Result(201, false, "-1", "支付发生错误");
        }
        String result_code = (String) closeMap.get("result_code");
        String err_code = (String) closeMap.get("err_code");
        if ("FAIL".equals(result_code) && "ORDERPAID".equals(err_code)) {
            Map<String, String> map = wxPayService.queryNative(orderId);
            orderService.updateStatusSuccess(orderId);
            return new Result(200, true, "1", "支付成功");
        }
        orderService.updateStatusSuccess(orderId);
        return new Result(201, false, "2", "超时未支付");
    }
}
